import React, { Suspense, lazy } from 'react';
import { createBrowserRouter, Navigate, RouteObject } from 'react-router-dom';
import { Spin } from '@douyinfe/semi-ui';
import Auth from '../pages/Auth';
import MainLayout from '../components/Layout/MainLayout';
import Dashboard from '../pages/Dashboard';
import { SysMenu } from '../api/menu';
import { routeManager } from '../utils/routeManager';

// 页面组件映射表
const pageComponents: Record<string, React.LazyExoticComponent<React.ComponentType<any>>> = {
  'Dashboard': lazy(() => import('../pages/Dashboard')),
  'UserManagement': lazy(() => import('../pages/system/UserManagement')),
  'RoleManagement': lazy(() => import('../pages/system/RoleManagement')),
  'PermissionManagement': lazy(() => import('../pages/system/PermissionManagement')),
  'MenuManagement': lazy(() => import('../pages/system/MenuManagement')),
  'PermissionAssignment': lazy(() => import('../pages/system/PermissionAssignment')),
};

// 加载组件的包装器
const LoadingWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => (
  <Suspense fallback={<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '200px' }}><Spin size="large" /></div>}>
    {children}
  </Suspense>
);

// 路由守卫组件
const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const token = localStorage.getItem('token');
  
  if (!token) {
    return <Navigate to="/login" replace />;
  }
  
  return <>{children}</>;
};

// 登录页面守卫
const LoginGuard: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const token = localStorage.getItem('token');
  
  if (token) {
    return <Navigate to="/dashboard" replace />;
  }
  
  return <>{children}</>;
};

// 使用路由管理器的方法
const getComponentName = routeManager.getComponentName.bind(routeManager);

// 将菜单转换为路由配置
const convertMenusToRoutes = (menus: SysMenu[]): RouteObject[] => {
  const routes: RouteObject[] = [];
  
  menus.forEach(menu => {
    // 只处理菜单类型（menuType: 2）和有路径的菜单
    if (menu.menuType === 2 && menu.menuPath) {
      const componentName = getComponentName(menu.menuPath);
      const Component = pageComponents[componentName];
      
      if (Component) {
        const route: RouteObject = {
          path: menu.menuPath.replace(/^\//, ''), // 移除开头的斜杠
          element: (
            <LoadingWrapper>
              <Component />
            </LoadingWrapper>
          ),
        };
        routes.push(route);
      }
    }
    
    // 递归处理子菜单
    if (menu.children && menu.children.length > 0) {
      routes.push(...convertMenusToRoutes(menu.children));
    }
  });
  
  return routes;
};

// 动态路由创建器
const createDynamicRouter = async (): Promise<ReturnType<typeof createBrowserRouter>> => {
  try {
    // 使用路由管理器获取用户菜单（带缓存）
    const userMenus = await routeManager.getUserMenus();
    
    // 获取路由统计信息
    const stats = routeManager.getRouteStats(userMenus);
    console.log('路由统计信息:', stats);
    
    // 转换菜单为路由
    const dynamicRoutes = convertMenusToRoutes(userMenus);
    
    // 验证路由配置
    if (!routeManager.validateRouteConfig(dynamicRoutes)) {
      console.warn('动态路由配置验证失败，使用备用路由');
      return createFallbackRouter();
    }
    
    // 创建完整的路由配置
    const routeConfig: RouteObject[] = [
      {
        path: '/',
        element: <Navigate to="/dashboard" replace />,
      },
      {
        path: '/login',
        element: (
          <LoginGuard>
            <Auth />
          </LoginGuard>
        ),
      },
      {
        path: '/register',
        element: (
          <LoginGuard>
            <Auth />
          </LoginGuard>
        ),
      },
      {
        path: '/',
        element: (
          <ProtectedRoute>
            <MainLayout />
          </ProtectedRoute>
        ),
        children: [
          // 默认仪表盘路由
          {
            path: 'dashboard',
            element: (
              <LoadingWrapper>
                <Dashboard />
              </LoadingWrapper>
            ),
          },
          // 动态生成的路由
          ...dynamicRoutes,
        ],
      },
      {
        path: '*',
        element: <Navigate to="/dashboard" replace />,
      },
    ];
    
    console.log(`成功创建动态路由，共 ${dynamicRoutes.length} 个路由`);
    return createBrowserRouter(routeConfig);
  } catch (error) {
    console.error('创建动态路由失败:', error);
    // 如果获取菜单失败，返回基础路由
    return createFallbackRouter();
  }
};

// 创建备用路由（当动态路由创建失败时使用）
const createFallbackRouter = (): ReturnType<typeof createBrowserRouter> => {
  return createBrowserRouter([
    {
      path: '/',
      element: <Navigate to="/dashboard" replace />,
    },
    {
      path: '/login',
      element: (
        <LoginGuard>
          <Auth />
        </LoginGuard>
      ),
    },
    {
      path: '/register',
      element: (
        <LoginGuard>
          <Auth />
        </LoginGuard>
      ),
    },
    {
      path: '/',
      element: (
        <ProtectedRoute>
          <MainLayout />
        </ProtectedRoute>
      ),
      children: [
        {
          path: 'dashboard',
          element: (
            <LoadingWrapper>
              <Dashboard />
            </LoadingWrapper>
          ),
        },
      ],
    },
    {
      path: '*',
      element: <Navigate to="/dashboard" replace />,
    },
  ]);
};

// 导出动态路由创建器
export const createRouter = createDynamicRouter;

// 导出备用路由（用于开发环境或路由创建失败时）
export const fallbackRouter = createFallbackRouter();

// 默认导出（保持向后兼容）
export default fallbackRouter;

// 路由工具函数
export { getComponentName, convertMenusToRoutes };